package com.yuandian.management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuandian.api.management.annotation.UpdateConfig;
import com.yuandian.api.management.entity.ConfAlarm;
import com.yuandian.api.management.entity.ConfAlarmDimension;
import com.yuandian.api.management.entity.ConfAlarmThreshold;
import com.yuandian.api.management.vo.AlarmsVo;
import com.yuandian.bpm.admin.api.entity.SysDictItem;
import com.yuandian.bpm.admin.api.feign.RemoteDictService;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.bpm.common.security.util.SecurityUtils;
import com.yuandian.constant.DictType;
import com.yuandian.management.mapper.ConfAlarmMapper;
import com.yuandian.management.service.ConfAlarmDimensionService;
import com.yuandian.management.service.ConfAlarmService;
import com.yuandian.management.service.ConfAlarmThresholdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 告警信息-Service实现
 * @author zfsn
 * @date 2023-4-4
 */
@Service
public class ConfAlarmServiceImpl extends ServiceImpl<ConfAlarmMapper, ConfAlarm>
		implements ConfAlarmService {

	@Autowired
	ConfAlarmMapper confAlarmMapper;

	@Autowired
	ConfAlarmDimensionService confAlarmDimensionService;


	@Autowired
	ConfAlarmThresholdService confAlarmThresholdService;

	@Autowired
	RemoteDictService remoteDictService;

	/**
	 * 通过主键查询数据
	 *
	 * @param ids 主键集合
	 * @return 通用返回对象
	 */
	@Override
	public List<ConfAlarm> listByIds(List<Integer> ids) {
		List<ConfAlarm> confAlarms = confAlarmMapper.listByIds(ids);
		if (confAlarms != null && confAlarms.size() > 0) {
			for (ConfAlarm confAlarm : confAlarms) {
				List<ConfAlarmDimension> dList = confAlarmDimensionService.queryDimensionByAlarmId(confAlarm.getId());
				confAlarm.setDimensions(dList);

				List<ConfAlarmThreshold> hList = confAlarmThresholdService.queryThresholdByAlarmId(confAlarm.getId());
				confAlarm.setThresholds(hList);
			}
		}
		Map<String, String> alarmObjType = remoteDictService.getDictByType(DictType.CONF_ALARM_INDICATOR_OBJ_TYPE).getData().stream().collect(Collectors.toMap(SysDictItem::getItemValue, SysDictItem::getLabel));
		for (ConfAlarm alarmPageRecord : confAlarms) {
			alarmPageRecord.setObjName(alarmObjType.get(String.valueOf(alarmPageRecord.getAlarmObjId())));
		}
		return confAlarms;
	}

	/**
	 * 分页查询
	 *
	 * @param confAlarm 筛选条件
	 * @return 通用返回对象
	 */
	@Override
	public Page<ConfAlarm> listPage(ConfAlarm confAlarm) {
		Page<ConfAlarm> confAlarmPage = confAlarmMapper.listPage(new Page<>(confAlarm.getPageNum(), confAlarm.getPageSize()), confAlarm);
		Map<String, String> alarmObjType = remoteDictService.getDictByType(DictType.CONF_ALARM_INDICATOR_OBJ_TYPE).getData().stream().collect(Collectors.toMap(SysDictItem::getItemValue, SysDictItem::getLabel));
		for (ConfAlarm alarmPageRecord : confAlarmPage.getRecords()) {
			alarmPageRecord.setObjName(alarmObjType.get(String.valueOf(alarmPageRecord.getAlarmObjId())));
		}
		return confAlarmPage;
	}

	/**
	 * 新增数据
	 *
	 * @param confAlarmVo 实例对象
	 * @return 通用返回对象
	 */
	@UpdateConfig
	@Override
	public R<String> saveConfig(AlarmsVo confAlarmVo) {
		ConfAlarm alarm = new ConfAlarm();
		alarm.setName(confAlarmVo.getName());
		alarm.setStartValue(confAlarmVo.getStartValue());
		alarm.setAlarmIndicatorId(confAlarmVo.getAlarmIndicatorId());
		alarm.setAlarmTemplateId(confAlarmVo.getAlarmTemplateId());
		alarm.setAlarmObjId(confAlarmVo.getAlarmObjId());
		alarm.setCreateBy(SecurityUtils.getUser().getName());
		alarm.setType(confAlarmVo.getType());
		super.save(alarm);

		ConfAlarm confAlarm = super.getOne(Wrappers.query(alarm));

		if (confAlarm.getId() != null && confAlarm.getId() > 0) {
			List<ConfAlarmDimension> confAlarmDimensions = confAlarmVo.getDimensions();
			List<ConfAlarmThreshold> confAlarmThresholds = confAlarmVo.getThresholds();

			if (confAlarmDimensions != null && !confAlarmDimensions.isEmpty()) {
				for (ConfAlarmDimension confAlarmDimension : confAlarmDimensions) {
					confAlarmDimension.setAlarmId(confAlarm.getId());
					confAlarmDimension.setIsDel(0);
					confAlarmDimensionService.save(confAlarmDimension);
				}
			}

			if (confAlarmThresholds != null && !confAlarmThresholds.isEmpty()) {
				for (ConfAlarmThreshold confAlarmThreshold : confAlarmThresholds) {
					confAlarmThreshold.setAlarmId(confAlarm.getId());
					confAlarmThreshold.setIsDel(0);
					confAlarmThresholdService.save(confAlarmThreshold);
				}
			}
		}
		return R.ok();
	}

	/**
	 * 通过主键更新数据
	 *
	 * @param confAlarmVo 实例对象
	 * @return 通用返回对象
	 */
	@UpdateConfig
	@Override
	public R<String> updateConfigById(AlarmsVo confAlarmVo) {

		ConfAlarm alarm = new ConfAlarm();
		alarm.setIsDel(0);
		alarm.setId(confAlarmVo.getId());
		alarm.setName(confAlarmVo.getName());
		alarm.setStartValue(confAlarmVo.getStartValue());
		alarm.setAlarmIndicatorId(confAlarmVo.getAlarmIndicatorId());
		alarm.setAlarmTemplateId(confAlarmVo.getAlarmTemplateId());
		alarm.setAlarmObjId(confAlarmVo.getAlarmObjId());
		alarm.setCreateBy(SecurityUtils.getUser().getName());
		alarm.setType(confAlarmVo.getType());
		super.updateById(alarm);
		if (confAlarmVo.getId() != null && confAlarmVo.getId() > 0) {

			//先软删除原来的维度和阀值，再增加新的
			UpdateWrapper<ConfAlarmDimension> dimensionsUpdateWrapper = new UpdateWrapper<>();
			dimensionsUpdateWrapper.eq("alarm_id", confAlarmVo.getId());
			confAlarmDimensionService.remove(dimensionsUpdateWrapper);

			UpdateWrapper<ConfAlarmThreshold> alarmThresholdUpdateWrapper = new UpdateWrapper<>();
			alarmThresholdUpdateWrapper.eq("alarm_id", confAlarmVo.getId());
			confAlarmThresholdService.remove(alarmThresholdUpdateWrapper);


			List<ConfAlarmDimension> confAlarmDimensions = confAlarmVo.getDimensions();
			List<ConfAlarmThreshold> confAlarmThresholds = confAlarmVo.getThresholds();

			if (confAlarmDimensions != null && !confAlarmDimensions.isEmpty()) {
				for (ConfAlarmDimension confAlarmDimension : confAlarmDimensions) {
					confAlarmDimension.setAlarmId(confAlarmVo.getId());
					confAlarmDimension.setIsDel(0);
					confAlarmDimensionService.save(confAlarmDimension);
				}
			}

			if (confAlarmThresholds != null && !confAlarmThresholds.isEmpty()) {
				for (ConfAlarmThreshold confAlarmThreshold : confAlarmThresholds) {
					confAlarmThreshold.setAlarmId(confAlarmVo.getId());
					confAlarmThreshold.setIsDel(0);
					confAlarmThresholdService.save(confAlarmThreshold);
				}
			}
		}
		return R.ok();
	}

	/**
	 * 修改是否启用状态
	 *
	 * @param confAlarm
	 * @return 结果
	 */
	@UpdateConfig
	@Override
	public R<String> updateAlarmEnable(ConfAlarm confAlarm) {

		// 更新状态前先判断该告警指标是否已经被删除
		if(confAlarm.getAlarmIndicatorId() == null){
			return R.failed("请求参数缺失告警指标id");
		}

		QueryWrapper<ConfAlarm> confAlarmQueryWrapper = new QueryWrapper<>();
		confAlarmQueryWrapper.eq("alarm_indicator_id", confAlarm.getAlarmIndicatorId());
		List<ConfAlarm> confAlarms = super.list(confAlarmQueryWrapper);
		if(confAlarms == null || confAlarms.isEmpty()) {
			return R.failed("该告警对应的指标已被删除，请刷新");
		}
		UpdateWrapper<ConfAlarm> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("id", confAlarm.getId());
		updateWrapper.set("is_enable", confAlarm.getIsEnable());
		if (super.update(updateWrapper)) {
			return R.ok();
		}
		return R.failed();
	}

	/**
	 * 查询指标类型(远程调用接口)
	 *
	 * @param category 实例对象
	 * @return 通用返回对象
	 */
	@Override
	public List<Integer> queryIndicator(String category) {
		return confAlarmMapper.queryIndicator(category);
	}

	/**
	 * 查询当前模板是否被告警引用到
	 *
	 * @param id
	 * @return 通用返回对象
	 */
	@Override
	public R queryAlarmByTemplateId(Integer id) {
		StringBuffer sb = new StringBuffer();
		String last = "";
		List<String> list = confAlarmMapper.queryAlarmByTemplateId(id);
		if(list != null && list.size() > 0) {
			for(String ss : list) {
				sb.append(ss);
				sb.append(" ， ");
			}
			last = sb.toString().substring(0, sb.toString().length() - 1);
		}
		return R.ok(last);
	}

	/**
	 * 查询当前指标是否被告警引用到
	 *
	 * @param id
	 * @return 通用返回对象
	 */
	@Override
	public R queryAlarmByIndicatorId(Integer id) {
		StringBuffer sb = new StringBuffer();
		String last = "";
		List<String> list = confAlarmMapper.queryAlarmByIndicatorId(id);
		if (list != null && list.size() > 0) {
			for (String ss : list) {
				sb.append(ss);
				sb.append("，");
			}
			last = sb.toString().substring(0, sb.toString().length() - 1);
		}
		return R.ok(last);
	}
}